package edu.mju.security.handler;

import edu.mju.security.utils.TokenUtils;
import edu.mju.serviceutils.ResponseCode;
import edu.mju.serviceutils.ResponseUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 退出操作处理器
 */
public class MyLogoutHandler implements LogoutHandler {

    private TokenUtils tokenUtils;

    private RedisTemplate redisTemplate;

    public MyLogoutHandler(TokenUtils tokenUtils, RedisTemplate redisTemplate) {
        this.tokenUtils = tokenUtils;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        //从header获取token
        String token = request.getHeader("token");
        //token不为空，移除token（删除redis中的token）
        if(!StringUtils.isEmpty(token)){
            //移除token
            tokenUtils.removeToken(token);
            //从token中获取用户名
            String username = tokenUtils.getTokenInfo(token);
            //移除redis数据
            redisTemplate.delete(username);
        }

        ResponseUtil.out(response, ResponseCode.success().message("退出成功！"));
    }
}
